/**********************************************************************\

 Copyright 2012 Diggory Blake

 This file is part of klip-engine

 This program is free software: you can redistribute it and/or modify
 it under the terms of the GNU General Public License as published by
 the Free Software Foundation, either version 3 of the License, or
 (at your option) any later version.

 This program is distributed in the hope that it will be useful,
 but WITHOUT ANY WARRANTY; without even the implied warranty of
 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 GNU General Public License for more details.

 You should have received a copy of the GNU General Public License
 along with this program.  If not, see <http://www.gnu.org/licenses/>.

\**********************************************************************/

#include "kview.h"
#include "kimage.h"
#include "kerror.h"
#include "kgraphics.h"
#include "krenderable.h"
#include "kperformance.h"

kView::kView(kGraphics* graphics) {
	_graphics = graphics;
	_camera = 0;
	_renderTarget = 0;
	_backdrop = kColor(0.0f, 0.0f, 0.0f);
	_backdropEnabled = true;

	kImage* backBuffer = graphics->getBackBuffer();
	setRenderTarget(backBuffer);
	setViewport(kRect(kVec2i(0, 0), backBuffer->getSize()));
}
kView::kView(kGraphics* graphics, kImage* renderTarget) {
	_graphics = graphics;
	_camera = 0;
	_renderTarget = 0;
	_backdrop = kColor(0.0f, 0.0f, 0.0f);
	_backdropEnabled = true;

	setRenderTarget(renderTarget);
	setViewport(kRect(kVec2i(0, 0), renderTarget->getSize()));
}
void kView::setRenderTarget(kImage* renderTarget) {
	if (renderTarget) {
		if (renderTarget->getOptions() & keImage_RenderTarget) {
			_renderTarget = renderTarget;
		} else {
			throw kError(_T("Image is not a render target!"));
		}
	} else {
		_renderTarget = 0;
	}
}
void kView::render(std::function<void (bool)> callback) {
	PERF_QUERY;

	_graphics->beginRender(this);

	if (callback)
		callback(true);

	kCollection<kRenderable*> renderables = this->getActors<kRenderable*>();
	std::sort(renderables.begin(), renderables.end(), [](kRenderable* a, kRenderable* b) {
		return a->getDepth() < b->getDepth();
	});

	for (auto i = renderables.begin(); i != renderables.end(); i++)
		(*i)->render(_graphics);

	if (callback)
		callback(false);

	_graphics->endRender();
}
